package com.tecnap.app.activity;

import com.tecnap.R;
import com.tecnap.app.ConfigEntity;
import com.tecnap.app.database.ConfigDataSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class ConfigActivity extends Activity {
	
	private ConfigEntity config;
	private ConfigDataSource configDataSource;
	
	// Layout views
	EditText editText;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.config);
		
		// Datbase table "config" Connector
		configDataSource = new ConfigDataSource(this);
		
		// Layout views
		editText = (EditText) findViewById(R.id.google_api_key);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		// Open the connection to database
		configDataSource.open();
		
		// Retrieve the config object from DB ...
		config = configDataSource.getConfig("google_api_key");
		
		// ... Then update the editText
		if( config != null ){
			editText.setText(config.getValue());
		}
	}
	
	@Override
	public void onStop() {
		super.onStop();
		// Close the connection to database
		configDataSource.close();
	}
	
	/**
	 * Save config into DB
	 * this handler is defined inside the layout XML
	 * see: res/layout/config.xml
	 * @param v
	 */
	public void saveConfig(View v) {
		configDataSource.setConfig("google_api_key", editText.getText().toString());
		
		// TODO
		// Raggruppare questo tipo di dialog di merda
		// in una classe di utilità statica!!!
		AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage("Impostazione salvata correttamente");
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}
	
}
